package com.java2007.hotel.controller;

import com.java2007.hotel.constant.ServletConstant;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/22
 **/
@WebServlet("/Controller")
@MultipartConfig
public class Controller extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        //获取要执行的方法

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String methodStr = request.getParameter("method");

        try {
            //获取类
            Class<? extends Controller> clazz = this.getClass();
            //获取方法
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class,HttpServletResponse.class);
            //调用方法
            Object object = method.invoke(this, request, response);
            if(object != null){
                if (object instanceof String){
                    String objUrl = (String) object;

                    //获取切割后的地址
                    String url = objUrl.substring(objUrl.indexOf(ServletConstant.COLON) + 1);

                    //判断转发还是重定向，或是输出字符串
                    //转发
                    if (objUrl.startsWith(ServletConstant.FORWARD)){
                        request.getRequestDispatcher(url).forward(request,response);
                    }
                    //重定向
                    else if (objUrl.startsWith(ServletConstant.REDIRECT)){
                        response.sendRedirect(request.getContextPath() + url);
                    }
                    //字符串
                    else {
                        response.getWriter().write(objUrl);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(ServletConstant.ERROR_MESSAGE);
        }


    }

}